import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { StorageService } from '../../providers/StorageService';
import { UserService } from '../../providers/UserService';

import { LoginPage } from '../login/login';

@Component({
  selector: 'page-forgotPassword',
  templateUrl: 'forgotPassword.html',
  providers: [UserService]
})
export class ForgotPasswordPage {
  forgotPasswordForm: FormGroup;

  constructor (
    private formBuilder: FormBuilder,
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    private storageService: StorageService,
    private userService: UserService
  ) {
    this.forgotPasswordForm = this.formBuilder.group({
      'valid_code': ['', [Validators.required]],
      'user_mobile': ['', [Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")]],
      'user_password': ['', [Validators.required, Validators.minLength(6)]],
      'user_repeat_password': ['', [Validators.required, Validators.minLength(6)]]
    });
  }

  save(user, _event) {
    let error_message = '保存失败';
    _event.preventDefault();

    if (user.user_password === user.user_repeat_password) {
      this.userService.forgotPassword(user).then(data => {
        if (data.status == 200)
        {
          this.navCtrl.push(LoginPage);
          let toast = this.toastCtrl.create({
            message: '保存成功.',
            duration: 3000,
            position: 'top',
            showCloseButton: true,
            closeButtonText: '关闭'
          });
          toast.present();
        }
        else
        {
          error_message = data.error.message;
          let toast = this.toastCtrl.create({
            message: error_message,
            duration: 3000,
            position: 'top',
            showCloseButton: true,
            closeButtonText: '关闭'
          });
          toast.present();
        }
      });
    } else {
      error_message = '密码与重复密码不相同';
      let toast = this.toastCtrl.create({
        message: error_message,
        duration: 3000,
        position: 'top',
        showCloseButton: true,
        closeButtonText: '关闭'
      });
      toast.present();
    }
  }
}
